#include <iostream>
#include <string>
#include <unistd.h>
#include <string.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Protocol.hpp"

// int main()
// {

//     return 0;
// }

// ./client server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:./client server_ip server_port" << std::endl;
        return 1;
    }

    // 获取ip和端口，建立对应的socket
    std::string server_ip = argv[1];
    int server_prot = std::stoi(argv[2]);
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket failed " << std::endl;
        return 2;
    }

    // 填充要连接的服务器的信息
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_prot);                  // 主机字节序转换为网络字节序
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str()); // 点分十进制转换为网络的二进制

    // client仍然不需要显式的进行bind
    // client也不能进行直接read或者write，需要先建立连接服务器(connect)
    // connect底层会进行bind，
    int n = ::connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); // TODO..
    if (n < 0)
    {
        std::cout << "connect failed" << std::endl;
        return 3;
    }

    std::string message;
    while (true)
    {
        int x, y;
        char oper;
        std::cout<< "input x: ";
        std::cin >> x;
        std::cout<< "input y: ";
        std::cin >> y;
        std::cout<< "input oper: ";
        std::cin >> oper;

        Request req(x, y, oper);    //创建需求对象

        //1.序列化,将我们的数据转换为序列化数据
        req.Serialize(message);

        //2.Encode，为序列化数据添加报头，形成一个传递的包裹
        Encode(message);

        //3.发送数据包
        n = ::send(sockfd, message.c_str(), message.size(), 0);

        if (n > 0)
        {
            char inbuffer[1024];
            //4.获得应答，应答对应的序列化数据，将其读取到inbuffer中
            int m = ::recv(sockfd, inbuffer, sizeof(inbuffer), 0);

            if (m > 0)
            {
                inbuffer[m] = 0;
                std::string package = inbuffer;     
                std::string content;

                //5.对接收到的序列化数据进行Decode -- 拆包
                Decode(package, &content);

                //6.对正文数据content进行反序列化，恢复原本的数据
                Response resp;
                resp.Deserialize(content);
                std::cout << resp.Result() << "[" << resp.Code() << "]" << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    ::close(sockfd);
    return 0;
}